import pandas as pd
import xgboost as xgb
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import train_test_split
from matplotlib import pyplot as plt
from lime.lime_tabular import LimeTabularExplainer
from sklearn.inspection import PartialDependenceDisplay
from sklearn.datasets import load_diabetes

# 加载糖尿病数据集
data = load_diabetes()
X = pd.DataFrame(data.data, columns=data.feature_names)
y = data.target

# 查看数据集的相关信息
print(X.head())
print("数据集特征形状：", data.data.shape)
print("目标变量形状：", data.target.shape)
print("数据集特征名称：", data.feature_names)

# 划分数据集（70%训练集，30%测试集）
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# 创建XGBoost回归模型
model = xgb.XGBRegressor(eval_metric='rmse')
# 训练模型
model.fit(X_train, y_train)
# 预测
y_pred = model.predict(X_test)
# 评估模型（使用均方误差MSE）
mse = mean_squared_error(y_test, y_pred)
print(f"模型均方误差: {mse:.4f}")

#PDP部分
# 选择要解释的特征
feature = 'bmi'
# 绘制PDP图
PartialDependenceDisplay.from_estimator(model, X_train, [feature])
plt.show()

#LIME部分
# 创建LIME解释器
explainer = LimeTabularExplainer(X_train.values, feature_names=X.columns, mode='regression')
# 选择一个样本进行解释
i = 10
exp = explainer.explain_instance(X_test.iloc[i].values, model.predict)
# 绘制LIME解释图
exp.show_in_notebook(show_table=True, show_all=False)